<template>
  <a-modal
    title="操作"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="所属公司">
          <a-select
            @change="handleProvinceChange"
            v-decorator="[ 'companyId', {rules: [{ required: true, message: '请选择所属公司' }],initialValue: defaultCompany}]"
            placeholder="请选择所属公司">
            <a-select-option :value="company.id" v-for="company in companyList" :key="company.id">
              {{company.name}}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="名称"
        >
          <a-input placeholder="名称"
                   v-decorator="[ 'name', {rules: [{ required: true, message: '请输入。。。' }]} ]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="每天最多抽奖次数"
        >
          <a-input
            placeholder="每天最多抽奖次数"
            v-decorator="['times', {rules: [{ required: true, message: '请输入数字', pattern: new RegExp(/^[1-9]\d*$/,'g'), }]}]"
          ></a-input>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="有效时间">
          <a-range-picker style="width: 100%" @change="onDateChange"
                          :format="dateFormat"
                          v-decorator="[ 'validTime', {rules: [{ required: true, message: '请选择时间' }]}]"
          />
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="背景图片(640*1136)"
        >

          <a-upload
            :action="this.$baseURL+'/common/upload/uploadImg'"
            listType="picture-card"
            :fileList="fileList"
            @preview="uploadPreview"
            @change="uploadChange"
          >
            <div v-if="fileList.length < 1">
              <a-icon type="plus"/>
              <div class="ant-upload-text">背景图片</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="uploadCancel">
            <img alt="example" style="width: 100%" :src="previewImage"/>
          </a-modal>
        </a-form-item>

        <a-divider/>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="转盘明细配置"
        >
          <div v-for="(item,i) in items" >
            <a-select style="width: 40%" placeholder="请选择商品" v-model="item.objectId">
              <a-select-option v-for="itemp in defaultConfig" :key="itemp.id">{{itemp.name}}({{itemp.id}})
              </a-select-option>
            </a-select>
            权重：
            <a-input-number style="width: 30%" v-model="item.rate"/>
            &#32;<a-button style="width: 18%" type="danger" @click="del(i)">删除</a-button>
          </div>
          <a-button @click="onAdd" type="primary" style="margin-top: 10px">添加</a-button>
        </a-form-item>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import { addOrUpdate, selectBigWheelDetailByBigWheelId } from '@/api/market/bigwheel'
  import {selectProductListByCompanyId} from '@/api/productService/product'
  import { selectAll } from '@/api/companyService/company'
  import pick from 'lodash.pick'
  import moment from 'moment'

  export default {
    //--############  data() ###############-->
    data() {
      return {
        dateFormat: 'YYYY-MM-DD',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        visible: false,
        confirmLoading: false,
        mdl: {},
        form: this.$form.createForm(this),

        isDisabled: false,
        defaultCompany: '',
        companyList: [],
        validTime: [],
        defaultConfig: [],
        config: [],
        items: [],
        company: {},
        fileList: [],
        previewImage: '',
        previewVisible: false,
        loading: '',
        newFileList:[]

      }
    },
    //--############  data() ###############-->

    created() {
      const _this = this
      selectAll().then(res => {
        _this.companyList = res.result
        _this.defaultCompany = this.companyList[0].id
        _this.company = {
          'companyId': this.defaultCompany,
          'sourceType': '2'
        }
        selectProductListByCompanyId(_this.company).then(res => {
          _this.defaultConfig = res.result
        })
      })
    },

    //--############  methods() ###############-->
    methods: {
      uploadCancel() {
        this.previewVisible = false
      },
      uploadPreview(file) {
        this.previewImage = file.url || file.thumbUrl
        this.previewVisible = true
      },
      uploadChange(info) {
        this.fileList = info.fileList
        if (info.file.status === 'done') {
          this.fileList.pop()
          this.fileList.push(info.file)
          this.newFileList = info.file.response
          this.$message.success(`${info.file.name} 上传成功`)
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败`)
        } else if (info.file.status === 'removed') {
          // deletePic(info.file.uid).then(res => {
          //
          // })
        }
      },
      getAllCompany: function() {
        // selectAllCompany().then(res => {
        //   if (res.code === 200) {
        //     this.companyList = res.result
        //     this.defaultCompany = this.companyList[0].id
        //   } else {
        //     this.$notification.error({
        //       message: '错误',
        //       description: res.message,
        //       duration: 4
        //     })
        //   }
        // })
      },
      handleProvinceChange: function(e) {
        /*通过商圈id查询该商圈下的商品*/
        console.log('handleProvinceChange', e)
        this.company = {
          'companyId': e,
          'sourceType': '2'
        }
        this.defaultCompany = e
        selectProductListByCompanyId(this.company).then(res => {
          console.log('查询商圈',res)
          this.defaultConfig = res.result
        })

        this.items = []
      },
      onAdd() {
        let cope = {
          objectId: '',
          objectType:'',
          rate: ''
        }
        this.items.push(cope)
      },
      del: function(index) {
        this.items.splice(index, 1)
      },
      onchange(e) {
        console.log(e)
      },
      onDateChange(e) {
        if (e.length == 0) {
          this.company = {
            'companyId': this.defaultCompany,
            'sourceType': '2'
          }
        } else {
          let beginDate = e[0].format('YYYY-MM-DD')+" 00:00:00"
          let endDate = e[1].format('YYYY-MM-DD')+" 23:59:59"
          this.company = {
            'companyId': this.defaultCompany,
            'beginTime': beginDate,
            'endTime': endDate,
            'sourceType': '2'
          }
        }
        selectProductListByCompanyId(this.company).then(res => {
          this.defaultConfig = res.result
        })
      },
      add() {
        this.isDisabled = false
        this.visible = true
        this.company = {
          'companyId': this.defaultCompany,
          'sourceType': '2'
        }
        selectProductListByCompanyId(this.company).then(res => {
          this.defaultConfig = res.result
        })
      },
      edit(record) {
        const _this = this
        /*查询所有的可以用的配置*/
        _this.company = {
          'companyId': record.companyId,
          'sourceType': '2'
        }
        selectBigWheelDetailByBigWheelId(record.id).then(res => {
          _this.items = res.result
        })
        selectProductListByCompanyId(_this.company).then(res => {
          _this.defaultConfig = res.result
        })

        if(record){
          this.fileList.push({"uid":"12345","url": record.backgroundUrl,"name":"333" })
        }
        this.isDisabled = true
        this.validTime.push(moment(record.beginTime))
        this.validTime.push(moment(record.endTime))
        record.validTime = this.validTime
        this.mdl = Object.assign({}, record)
        this.visible = true
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(record, 'name', 'validTime', 'times', 'companyId'))
        })
        // selectBigWheelDetailByBigWheelId(record.id).then(res => {
        //   console.log('转盘盘明细',res)
        //   this.items = res.result
        // })
      },
      close() {
        this.$emit('close')
        this.visible = false
        this.form.resetFields()
        this.mdl = {}
        this.config = []
        this.items = []
        this.validTime = []
        this.fileList = []
      },
      handleOk() {
        const _this = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          // 验证表单没错误
          if (!err) {
            values.beginTime = values.validTime[0].format('YYYY-MM-DD')+" 00:00:00"
            values.endTime = values.validTime[1].format('YYYY-MM-DD')+" 23:59:59"
            values.id = this.mdl.id
            let rates = 0
            console.log('122222',_this.items)
            for (let i = 0; i < _this.items.length; i++) {
              rates = rates + _this.items[i].rate
            }
            if (rates > 100) {
              _this.$message.warn('权重之和不能超过100！请核对')
              return
            }
            _this.confirmLoading = true
            values.bigWheelDetailList = _this.items
          let backgroundUrl = this.newFileList.url
            values.backgroundUrl = backgroundUrl
            // 模拟后端请求 2000 毫秒延迟
            console.log('form values', values)
            addOrUpdate(values).then((res) => {
              if (res.code === 200) {
                _this.$message.success('保存成功')
                _this.$emit('ok')
                _this.close()
              } else {
                this.$notification.error({
                  message: '错误',
                  description: res.message,
                  duration: 4
                })
              }
            }).catch(() => {
              // Do something
            }).finally(() => {
              _this.confirmLoading = false
            })
          }
        })
      },
      handleCancel() {
        this.close()
      }
    }
    //--############  methods() ###############-->
  }

  function getBase64(img, callback) {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result))
    reader.readAsDataURL(img)
  }

  // function packageFileList(fileList) {
  //   let fileLists = []
  //   for (let i = 0; i < fileList.length; i++) {
  //     if (fileList[i].response != undefined) {
  //       fileLists.push(fileList[i].response)
  //     } else {
  //       fileLists = fileList
  //     }
  //   }
  //   return fileLists
  // }
</script>

<style scoped>

</style>
